package com.jml.session;

import com.jml.executor.BaseExecutor;
import com.jml.proxy.MapperProxyFactory;
import com.jml.statement.MappedStatement;
import java.util.List;


public class DefaultSqlSession implements SqlSession {
    private final Configuration configuration;
    private BaseExecutor executor;

    public DefaultSqlSession(Configuration configuration, BaseExecutor executor) {
        this.configuration = configuration;
        this.executor = executor;
    }

    @Override
    public <T> T getMapper(Class<T> type) throws Exception {
        // 1.查询configuration 是否有注册该Mapper接口
        MapperProxyFactory mapperProxyFactory = (MapperProxyFactory) configuration.getMapper(type);
        if (mapperProxyFactory == null) {
            throw new Exception("Type " + type + " is not known to the MapperRegistry.");
        }
        return (T) mapperProxyFactory.newInstance(this);
    }

    @Override
    public <T> T selectOne(MappedStatement statement) throws Exception {
        List<T> list = this.selectList(statement);
        if (list.size() == 1) {
            return list.get(0);
        } else if (list.size() > 1) {
            throw new Exception("Expected one result (or null) to be returned by selectOne(), but found: " + list.size());
        } else {
            return null;
        }
    }

    @Override
    public <T> List<T> selectList(MappedStatement ms) {
        ms.setConfiguration(configuration);
        return executor.query(ms);
    }
}
